<template>
  <el-dialog :title="id ? '修改角色' : '新增角色'" :visible.sync="dialogFormVisible" width="600px">
    <el-form
      ref="dataForm"
      :rules="rules"
      :model="temp"
      label-position="left"
      label-width="140px"
      style="margin: 0 30px"
    >
      <template>
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="temp.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色权限" prop="permissions">
          <div v-for="item in permissionsOptions" :key="item.code">
            <el-checkbox v-model="item.checkAll" @change="handleCheckAllChange(item)">{{
              item.name
            }}</el-checkbox>
            <div style="margin-left: 20px">
              <el-checkbox
                @change="handleCheckedCitiesChange(item)"
                v-for="sub in item.sub"
                :key="sub.code"
                :label="sub.code"
                v-model="item.ids"
              >
                {{ sub.name }}
              </el-checkbox>
            </div>
          </div>
        </el-form-item>
      </template>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取消</el-button>
      <el-button type="primary" @click="saveData">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getDetail, add, edit } from '@/api/roles'
import { getPermissionsList } from '@/api/common'
const rule = [{ required: true, message: '必填项不能为空' }]
export default {
  name: 'RolesEdit',

  data() {
    return {
      dialogFormVisible: false,
      id: '',
      temp: {
        name: '',
        permissions: []
      },
      rules: {
        name: rule
      },

      permissionsOptions: [],
      permissionsList: []
    }
  },

  created() {
    this._getPermissionsList()
  },
  methods: {
    _getPermissionsList() {
      getPermissionsList().then((res) => {
        this.permissionsList = res.data
        this.permissionsOptions = res.data.map((item) => {
          return {
            ...item,
            checkAll: false,
            ids: item.code === 'order' ? ['refund_operation'] : [],
            sub: item.sub.map((sub) => {
              return {
                ...sub,
                checked: !!(sub.code === 'refund_operation')
              }
            })
          }
        })
      })
    },
    handleCreate() {
      this.id = ''
      this.temp = {
        name: '',
        permissions: ['refund_operation']
      }
      this._getPermissionsList()
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs.dataForm.clearValidate()
      })
    },
    /**
     * @description: 全选
     * @param {*} item
     * @return {*}
     */
    handleCheckAllChange(info) {
      const subs = [...info.sub.map((item) => item.code), info.code]

      if (info.checkAll) {
        const list = [...this.temp.permissions, ...subs]
        this.permissionsOptions = this.permissionsOptions.map((item) => {
          return {
            ...item,
            ids: info.code === item.code ? subs : item.ids,
            sub: item.sub.map((sub) => {
              return {
                ...sub,
                checked: true
              }
            })
          }
        })

        this.temp.permissions = [...new Set(list)]
      } else {
        const list = this.temp.permissions.filter((item) => !subs.includes(item))
        this.temp.permissions = [...new Set(list)]

        this.permissionsOptions = this.permissionsOptions.map((item) => {
          return {
            ...item,
            ids: info.code === item.code ? [] : item.ids,
            sub: item.sub.map((sub) => {
              return {
                ...sub,
                checked: false
              }
            })
          }
        })
      }
      console.log('this.temp.permissions', this.temp.permissions)
    },
    handleCheckedCitiesChange(value) {
      const sub_all_codes = [
        ...this.permissionsOptions
          .find((item) => item.code === value.code)
          .sub.map((item) => item.code)
      ]
      console.log('value', value)
      const difference = sub_all_codes.filter((item) => !value.ids.includes(item))
      console.log('difference', difference)
      if (difference.length === 0) {
        value.checkAll = true
      } else {
        value.checkAll = false
      }

      const sub_codes = sub_all_codes.filter((item) => !difference.includes(item))
      const new_codes = sub_codes.length === 0 ? [] : [...sub_codes, value.code]
      this.temp.permissions = [
        ...new Set([
          ...this.temp.permissions.filter((item) => !difference.includes(item)),
          ...new_codes
        ])
      ]
      console.log('this.temp.permissions', this.temp.permissions)
    },
    // 编辑
    handleEdit(id) {
      // this._getPermissionsList()
      getDetail(id).then((res) => {
        this.id = id
        Object.assign(this.temp, res.data)
        console.log('this.permissionsOptions', this.permissionsOptions)
        this.permissionsOptions = this.permissionsOptions
          .map((item) => {
            return {
              ...item,
              checkAll: false,
              sub: item.sub.map((sub) => {
                return {
                  ...sub,
                  checked: !!res.data.permissions.includes(sub.code)
                }
              })
            }
          })
          .map((item) => {
            const ids = item.sub.filter((sub) => sub.checked).map((sub) => sub.code)
            return {
              ...item,
              ids,
              checkAll:
                (item.sub.length === 0 && res.data.permissions.includes(item.code)) ||
                (item.sub.length > 0 && ids.length === item.sub.length) // 一级权限中没有二级权限，或者二级权限全选
            }
          })

        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      })
    },
    // 保存
    saveData() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          const d = JSON.parse(JSON.stringify(this.temp))
          const p = this.id ? edit(this.id, d) : add(d)
          p.then(() => {
            this.$parent.fetchData()
            this.dialogFormVisible = false
            this.$parent.$notify({
              title: '成功',
              message: this.id ? '修改成功' : '添加成功',
              type: 'success'
            })
          })
        }
      })
    }
  }
}
</script>
<style scoped>
.item-p {
  margin: 0;
  /* height: 1px; */
}
</style>
